package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"lesson25/models"
	"net/http"
)
/*
 url    -->controller  -->logic   -->model
请求来了  -->控制器       -->业务逻辑 -->模型层的增删改查
*/
func IndexHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", nil)
}
func CreateToDo(c *gin.Context) {
	//前端页面填写待办事项，点击提交按钮，会发请求到这里
	//1.从请求中把数据拿出来
	var todo models.ToDo
	c.BindJSON(&todo)
	fmt.Printf("POST do shouldbind:%#v \n", todo)
	//2.存入数据库
	if err1:=models.CreateAToDo(&todo);err1!=nil {
		//3.返回响应
		c.JSON(http.StatusOK, gin.H{"error": err1.Error()})
	} else {
		//3.返回响应
		c.JSON(http.StatusOK, todo)
		//c.JSON(http.StatusOK,gin.H{
		//	"code":2000,
		//	"msg":"success",
		//	"data":todo,
		//})
	}
}

func GetToDoList(c *gin.Context) {
	//查询todo表里面所有数据
	todolist,err2 := models.GetAllToDo()
	if err2 != nil {
		c.JSON(http.StatusOK, gin.H{"error": err2.Error()})
	} else {
		c.JSON(http.StatusOK, todolist)
	}
	//fmt.Printf("GET do shouldbind:%#v \n", todolist)
	for _,v:=range todolist{
		fmt.Printf("GET do shouldbind:%#v \n", v)
	}

}

func UpdateAToDo(c *gin.Context) {
	id, ok := c.Params.Get("id")
	if !ok {
		c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
		return
	}
	todo,err3 := models.GetAToDO(id)
	if err3 != nil {
		c.JSON(http.StatusOK, gin.H{"error": err3.Error()})
		return
	}
	fmt.Printf("PUT undo shouldbind:%#v \n", *todo)
	c.BindJSON(todo)
	fmt.Printf("PUT do shouldbind:%#v \n", *todo)
	err4 := models.UpdateAToDo(todo)
	if  err4 != nil {
		c.JSON(http.StatusOK, gin.H{"error": err4.Error()})
		return
	} else {
		c.JSON(http.StatusOK, todo)
	}
}


func DeleteToDo(c *gin.Context) {
	id, ok := c.Params.Get("id")
	if !ok {
		c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
		return
	}
	err5:=models.DeleteAToDO(id)
	if err5 != nil {
		c.JSON(http.StatusOK, gin.H{"error": err5.Error()})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{id: "deleted"})
	}
	//物理删除
	//DB.Debug().Unscoped().Where("id=?",id).Delete(&ToDo{})
}
